package com.weilele.mvvm.base.helper.annotation

import androidx.appcompat.app.AppCompatActivity
import androidx.fragment.app.Fragment
import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStoreOwner
import com.weilele.mvvm.base.MvvmViewModel
import com.weilele.mvvm.base.livedata.appCompatActivity
import java.lang.reflect.Field


/**
 * 处理fragment中
 * [MvvmViewModel]
 * [MvvmActivityViewModel]
 * [MvvmVLayoutAdapter]
 * 注解
 */
fun Fragment?.dealViewModelAnnotation() {
    this.dealViewModelAnnotation(this, this?.appCompatActivity)
}

/**
 * 处理activity中
 * [MvvmViewModel]
 * [MvvmActivityViewModel]
 * [MvvmVLayoutAdapter]
 * 注解
 */
fun AppCompatActivity?.dealViewModelAnnotation() {
    this.dealViewModelAnnotation(null, this)
}


fun Any.getAllFields(): Array<Field> {
//    val fields = mutableListOf<Field>()
//    this ?: return fields
//    fields.addAll(javaClass.declaredFields)
//    fields.addAll(javaClass.fields)
    return javaClass.declaredFields
}

/**
 * 编译注解
 */
private fun Any?.dealViewModelAnnotation(
    fragment: Fragment?,
    activity: AppCompatActivity?
) {
    this ?: return
    getAllFields().forEach { field ->
        when {
            field.getAnnotation(com.weilele.mvvm.base.helper.annotation.MvvmViewModel::class.java) != null -> {//创建MvvmViewModel
                val owner = when {
                    fragment != null -> {
                        fragment
                    }
                    activity != null -> {
                        activity
                    }
                    else -> {
                        null
                    }
                }
                createViewModel(field, owner)
            }
            field.getAnnotation(com.weilele.mvvm.base.helper.annotation.MvvmActivityViewModel::class.java) != null -> {//创建ActivityViewModel
                val owner = when {
                    fragment != null -> {
                        fragment.appCompatActivity
                    }
                    activity != null -> {
                        activity
                    }
                    else -> {
                        null
                    }
                }
                createViewModel(field, owner)
            }
        }
    }
}

/**
 * 创建viewModel对象
 */
private fun Any.createViewModel(field: Field, owner: ViewModelStoreOwner?) {
    owner ?: return
    field.isAccessible = true
    val viewModel = ViewModelProvider(owner).get(field.type as Class<ViewModel>)
    field.set(this, viewModel)
    if (viewModel is MvvmViewModel) {
        viewModel.autoCreateModel()
    }
}

/**
 * 创建Model对象
 */
fun MvvmViewModel?.autoCreateModel() {
    this ?: return
    getAllFields().forEach { field ->
        if (field.getAnnotation(MvvmModel::class.java) != null) {
            field.isAccessible = true
            field.set(this, createModel(field.type))
        }
    }
}


